package com.example.jsonhelper

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import com.example.jsonhelper.framework.LyyActivityCollector
import com.example.jsonhelper.framework.LyyBaseActivity
import com.example.jsonhelper.framework.widget.LyyDialog

class MainActivity : LyyBaseActivity() {
    private lateinit var et: EditText
    private lateinit var btn:Button
    private lateinit var menu: Menu
    companion object{
        const val DATA_KEY = "data_key"
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initViews()
        initTitleBar(title = "JSON工具", isShowBackIcon = false)
        initEvents()
    }

    private fun initViews() {
        et=findViewById(R.id.et)
        btn=findViewById(R.id.btn)
    }

    private fun initEvents(){
        btn.setOnClickListener {
            val intent=Intent(this,ResultActivity::class.java)
            intent.putExtra(DATA_KEY,et.text.toString())
            startActivity(intent)
        }
        et.addTextChangedListener(object :TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                val content = s?.toString()
                btn.isEnabled=content!=null&&content.isNotEmpty()
                if (menu!=null){
                    menu.findItem(R.id.clear_text).isVisible=content!=null&&content.isNotEmpty()
                }
            }
        })
    }



    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        if (menu != null) {
            this.menu=menu
        }
        menuInflater.inflate(R.menu.main_act_menu,menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.exit->{
                val lyyDialog = LyyDialog(this)
                lyyDialog.setContent("您确定要退出程序吗？")
                lyyDialog.setBtnsClickListener(object:LyyDialog.OnBtnsClickListener{
                    override fun onNegativeBtnClick(dialog: LyyDialog) {
                        lyyDialog.dismiss()
                    }

                    override fun onPositiveBtnClick(dialog: LyyDialog) {
                        lyyDialog.dismiss()
                        LyyActivityCollector.exitApp()
                    }

                })
                lyyDialog.show()
            }
            R.id.clear_text->{
                et.setText("")
            }
            else->{}
        }
        return true
    }
}